package progress.exa6;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;

public class LockWriteFile extends Thread {

    public void run(){
        long start = System.currentTimeMillis();
        //创建文件对象
        File file = new File("test.txt");
        try {
            //如果文件不存在，创建之
            if(!file.exists()){
                if(file.createNewFile()){
                    System.out.println("创建成功！！");
                }else {
                    System.out.println("创建失败！！");
                }
            }
            //对该文件加锁
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            FileChannel fileChannel = randomAccessFile.getChannel();
            FileLock fileLock = null;

            while(true){
                try {
                    fileLock = fileChannel.tryLock();
                    break;
                } catch (Exception e) {
                    System.out.println("有其他线程正在操作该文件，当前线程"+Thread.currentThread().getName()+"休眠1000毫秒");
                    sleep(1000);
                }
            }

            for(int i=1;i<=1000;i++){
                sleep(10);
                StringBuffer sb = new StringBuffer();
                sb.append("这是第").append(i).append("行对应的数据");
                sb.append("\n");
                randomAccessFile.seek(file.length());
                randomAccessFile.write(sb.toString().getBytes(StandardCharsets.UTF_8));
            }
            //释放锁
            fileLock.release();
            //关闭信道
            fileChannel.close();
            //关闭流
            randomAccessFile.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程:"+Thread.currentThread().getName()+",写文件耗时： "+(System.currentTimeMillis()-start)+"毫秒");
    }

}
